package model

import (
	"database/sql/driver"
	"fmt"
	"strings"
	"time"
)

type JsonTime time.Time

const (
	TimeFormatter = "2006-01-02 15:04:05"
	TimeZone      = "Asia/Shanghai"
)

// UnmarshalJSON implements json unmarshal interface.
func (t *JsonTime) UnmarshalJSON(data []byte) (err error) {
	dateString := string(data)
	dateString = dateString[1 : len(dateString) - 1]
	dateArray := strings.Fields(dateString)
	if len(dateArray) == 1 {
		dateString += " 00:00:00"
	}

	//now, err := time.ParseInLocation(`"` + TimeFormatter + `"`, dateString, time.Local)
	now, err := time.ParseInLocation(TimeFormatter, dateString, time.Local)
	*t = JsonTime(now)
	return nil
}

// MarshalJSON implements json marshal interface.
func (t JsonTime) MarshalJSON() ([]byte, error) {
	b := make([]byte, 0, len(TimeFormatter) + 2)
	b = append(b, '"')
	b = time.Time(t).AppendFormat(b, TimeFormatter)
	b = append(b, '"')
	return b, nil
}

func (t JsonTime) String() string {
	return time.Time(t).Format(TimeFormatter)
}

func (t JsonTime) local() time.Time {
	loc, _ := time.LoadLocation(TimeZone)
	return time.Time(t).In(loc)
}

// Value ...
func (t JsonTime) Value() (driver.Value, error) {
	var zeroTime time.Time
	var ti = time.Time(t)
	if ti.UnixNano() == zeroTime.UnixNano() {
		return nil, nil
	}
	return ti, nil
}

// Scan valueof time.Time 注意是指针类型 method
func (t *JsonTime) Scan(v interface{}) error {
	value, ok := v.(time.Time)
	if ok {
		*t = JsonTime(value)
		return nil
	}
	return fmt.Errorf("can not convert %v to timestamp", v)
}
